import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/controller/evaluation.dart';
import 'package:ichinesereader/models/book/BookArguments.dart';
import 'package:ichinesereader/models/book/BookItem.dart';
import 'package:ichinesereader/pages/book/bookQuizEditor.dart';
import 'package:ichinesereader/pages/word/WordCardQuiz.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/constants.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:universal_html/html.dart' as uHtml;
import '../../controller/assessments.dart';
import '../../pages/book/bookGrammar.dart';
import '../../pages/book/bookQuickReview.dart';
import '../../themes/appTheme.dart';
import '../dialogs/evaBookDialog.dart';
import 'package:just_the_tooltip/just_the_tooltip.dart';
import 'package:ichinesereader/controller/knowledgeword.dart';

class BookGridWithCheckBox extends StatefulWidget {
  BookGridWithCheckBox({
    Key? key,
    required this.books,
    required this.readingType,
    this.assignmentId,
  }) : super(key: key);

  final List<BookItem> books;
  final String? assignmentId;
  final NanhaiBookReadingTypes readingType;

  @override
  _BookGridWithCheckBoxState createState() => _BookGridWithCheckBoxState();
}

class _BookGridWithCheckBoxState extends State<BookGridWithCheckBox> {
  final BooksController _bookcontroller = Get.find();
  final box = Hive.box('appconfig');
  late String userName;
  bool setEvaluation = true;
  late ScrollController _scrollController;

  @override
  void initState() {
    _scrollController = ScrollController();
    _scrollController.addListener(_scrollListener);

    userName = box.get(CacheManagerKey['username'].toString());
    box.put(CacheManagerKey['_readingType'],
        widget.readingType.toString().split('.')[1]);
    setEvaluation = box.get('evaluation') ?? true;
    super.initState();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _bookcontroller.setCurrentPage(0);
    super.dispose();
  }

  _scrollListener() {
    if (_scrollController.offset >=
            _scrollController.position.maxScrollExtent &&
        !_scrollController.position.outOfRange) {
      if (widget.readingType == NanhaiBookReadingTypes.library &&
          widget.books.length >= Constants.pageLimit) {
        _bookcontroller.fetchMoreOpenReadingItems();
      } else if (widget.readingType == NanhaiBookReadingTypes.leveled &&
          widget.books.length >= Constants.pageLimit) {
        _bookcontroller.fetchMoreLevelReadingItems();
      } else if (widget.readingType == NanhaiBookReadingTypes.search &&
          widget.books.length >= Constants.pageLimit) {
        // for home page search y level and topic
        _bookcontroller.fetchMoreSearchedBookItems();
      } else if (widget.readingType == NanhaiBookReadingTypes.favorite &&
          widget.books.length >= Constants.pageLimit) {
        _bookcontroller.fetchMoreMyFavoriteReadingItemsByFolder();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    bool isStudent = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Student;
    bool isIndividual = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Individual;
    bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    bool isAdmin = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_SchoolAdmin;
    return GridView.builder(
        padding: EdgeInsets.zero,
        controller: _scrollController,
        gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
            maxCrossAxisExtent: 240,
            childAspectRatio: 156 / 200,
            crossAxisSpacing: 20,
            mainAxisSpacing: 20),
        itemCount: widget.books.length,
        itemBuilder: (BuildContext ctx, index) {
          BookItem currentBook = widget.books[index];
          String bid = currentBook.bookId ?? '';
          String btitle = currentBook.bookTitle ?? '';
          String bcode = currentBook.bookCode ?? '';
          String bimage = currentBook.bookImageLink ?? '';
          String color = currentBook.color ?? '';
          String bookLevel = currentBook.bookLevel ?? '';
          String desc = currentBook.description ?? '';
          bool readComplete = currentBook.readComplete ?? false;
          bool quizAvailable = currentBook.quizAvailable ?? false;
          bool pass = currentBook.pass ?? false;
          bool inFolder = currentBook.inFolder ?? false;
          bool inAudioPlaylist = currentBook.inAudioPlaylist ?? false;
          // //String grammar = currentBook.grammar ?? '';
          String quickReview = currentBook.quickReview ?? '';
          String grammar = currentBook.grammar ?? '';
          String word = currentBook.word ?? '';

          Color quizColor = hexStringToHexInt('#ff7043');
          if (pass) {
            quizColor = hexStringToHexInt('#ffc107');
          }

          return Container(
            ////////////SINGLE BOOK BACKGROUND//////////////////
            decoration: BoxDecoration(
              color: Get.isDarkMode
                  ? AppTheme.colors.darkTheme2
                  : Colors.white.withOpacity(0.3),
              borderRadius: BorderRadius.circular(4.5),
              boxShadow: Get.isDarkMode
                  ? null
                  : [
                      BoxShadow(
                        blurRadius: 12,
                        spreadRadius: 1,
                        color: Get.isDarkMode
                            ? Color(0xff555555)
                            : Colors.black.withOpacity(0.1),
                        offset: Offset(1, 1),
                      ),
                    ],
            ),
            padding: EdgeInsets.fromLTRB(12.0, 12.0, 0.0, 0.0),
            /////book and title column and icon column/////
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: <Widget>[
                      Expanded(
                        child: MouseRegion(
                            cursor: SystemMouseCursors.click,
                            child: GestureDetector(
                              onTap: () {
                                //_bookcontroller.setCurrentBook(currentBook);
                                if (GetPlatform.isWeb) {
                                  uHtml.window.localStorage['bookBasePath'] =
                                      'https://resources.ichinesereader.com/books/$bcode/assets';
                                  uHtml.window.localStorage['bookCode'] = bcode;
                                  uHtml.window.localStorage['bookID'] = bid;
                                  uHtml.window.localStorage['currentPageNum'] =
                                      '0';
                                  uHtml.window.localStorage['totalPageNum'] =
                                      '0';
                                }

                                String? level;
                                String? progress;
                                int? _userLevel;
                                bool callEva = false;
                                try {
                                  level = box
                                      .get('UserLevel')
                                      .toString()
                                      .replaceAll('level', '');

                                  _userLevel = int.tryParse(level) ?? 0;

                                  progress =
                                      box.get('UserLevelPercentage').toString();
                                } catch (error) {
                                  Log.debug(error.toString());
                                }
                                if (bookLevel == level &&
                                    setEvaluation == true &&
                                    (isStudent || isIndividual) &&
                                    (widget.readingType ==
                                            NanhaiBookReadingTypes.library ||
                                        widget.readingType ==
                                            NanhaiBookReadingTypes.leveled)) {
                                  //æš‚æ—¶æŠŠevaluationä¹¦é™å®šåœ¨1-12çº§æ‰ä¼šè·³ä¹¦
                                  if (_userLevel! > 0 && _userLevel < 13) {
                                    String last = progress!
                                        .substring(progress.length - 1);
                                    callEva = last.contains('4') ||
                                        last.contains('8');
                                    // callEva =
                                    //     last.contains('4') || last.contains('8');
                                    //callEva = true;
                                  }
                                }
                                box.put(CacheManagerKey['_callEva'].toString(),
                                    callEva);
                                if (callEva == false) {
                                  if ((GetPlatform.isDesktop ||
                                          GetPlatform.isMacOS) &&
                                      !GetPlatform.isWeb) {
                                    launchInWebViewWithJavaScript(
                                        '${Constants.BaseURL}icr/student/book/$bid');
                                  } else if (GetPlatform.isWeb) {
                                    box.put(
                                        CacheManagerKey['_quizAvailable']
                                            .toString(),
                                        quizAvailable);
                                    bool readComplete =
                                        currentBook.readComplete ?? false;
                                    box.put(
                                        CacheManagerKey['_readComplete']
                                            .toString(),
                                        readComplete);

                                    if (isTeacher || isAdmin) {
                                      launchInWebViewWithJavaScript(
                                          '${Constants.BaseURL}icr/student/book/$bid');
                                    } else {
                                      Navigator.pushNamed(
                                          context, '/student/book',
                                          arguments: BookArguments(
                                              bid,
                                              bcode,
                                              btitle,
                                              widget.assignmentId ?? null,
                                              widget.readingType,
                                              userName));
                                    }
                                  } else {
                                    String viewMode =
                                        widget.books[index].viewMode ??
                                            'LANDSCAPE';
                                    box.put(
                                        CacheManagerKey['_viewMode'].toString(),
                                        viewMode.toString());
                                    bool quizAvailable =
                                        currentBook.quizAvailable ?? false;
                                    box.put(
                                        CacheManagerKey['_quizAvailable']
                                            .toString(),
                                        quizAvailable);
                                    bool readComplete =
                                        currentBook.readComplete ?? false;
                                    box.put(
                                        CacheManagerKey['_readComplete']
                                            .toString(),
                                        readComplete);

                                    Navigator.pushNamed(
                                        context, '/student/book',
                                        arguments: BookArguments(
                                            bid,
                                            bcode,
                                            btitle,
                                            widget.assignmentId ?? null,
                                            widget.readingType,
                                            userName));
                                  }
                                } else {
                                  final EvaluationController
                                      _evaluationController = Get.find();

                                  _evaluationController
                                      .fetchEvaluationRandomBook(level!)
                                      .then((status) {
                                    if (status.status == 1000) {
                                      box.put(
                                          CacheManagerKey['_quizAvailable']
                                              .toString(),
                                          false);

                                      showDialog(
                                          context: context,
                                          builder: (BuildContext context) {
                                            return EvaBookDialog(
                                                title: 'Evaluation Book'.tr,
                                                message:
                                                    'Please complete this evaluation book to continue!'
                                                        .tr,
                                                level: level!,
                                                from: 'library',
                                                userName: userName);
                                          });
                                    } else {
                                      String viewMode =
                                          widget.books[index].viewMode ??
                                              'LANDSCAPE';
                                      box.put(
                                          CacheManagerKey['_viewMode']
                                              .toString(),
                                          viewMode.toString());
                                      bool quizAvailable =
                                          currentBook.quizAvailable ?? false;
                                      box.put(
                                          CacheManagerKey['_quizAvailable']
                                              .toString(),
                                          quizAvailable);
                                      bool readComplete =
                                          currentBook.readComplete ?? false;
                                      box.put(
                                          CacheManagerKey['_readComplete']
                                              .toString(),
                                          readComplete);

                                      Navigator.pushNamed(
                                          context, '/student/book',
                                          arguments: BookArguments(
                                              bid,
                                              bcode,
                                              btitle,
                                              widget.assignmentId ?? null,
                                              widget.readingType,
                                              userName));
                                    }
                                  });
                                }
                              },
                              child: JustTheTooltip(
                                backgroundColor: Get.isDarkMode
                                    ? Get.theme.primaryColorDark
                                    : Get.theme.primaryColorLight,
                                preferredDirection: AxisDirection.right,
                                elevation: 4.0,
                                content: Container(
                                  padding: EdgeInsets.all(12.0),
                                  width: 180,
                                  color: Colors.transparent,
                                  child: Text(
                                    desc != '' ? desc : btitle,
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: Get.isDarkMode
                                          ? Colors.black
                                          : Colors.black87,
                                    ),
                                  ),
                                ),
                                child: Image.network(
                                  bimage,
                                  height: 200.0,
                                  width: 156,
                                  fit: BoxFit.cover,
                                  errorBuilder: (context, error, stackTrace) {
                                    return Image.asset(
                                        'assets/images/imagenotavailable.png',
                                        height: 200.0,
                                        width: 156,
                                        fit: BoxFit.cover);
                                  },
                                ),
                              ),
                            )),
                      ),
                      MouseRegion(
                          cursor: SystemMouseCursors.click,
                          child: GestureDetector(
                            onTap: () {
                              if (GetPlatform.isWeb) {
                                uHtml.window.localStorage['bookBasePath'] =
                                    'https://resources.ichinesereader.com/books/$bcode/assets';
                                uHtml.window.localStorage['bookCode'] = bcode;
                                uHtml.window.localStorage['bookID'] = bid;
                                uHtml.window.localStorage['currentPageNum'] =
                                    '0';
                                uHtml.window.localStorage['totalPageNum'] = '0';
                              }
                              String? level;
                              String? progress;
                              bool callEva = false;
                              int? _userLevel;
                              try {
                                level = box
                                    .get('UserLevel')
                                    .toString()
                                    .replaceAll('level', '');
                                _userLevel = int.tryParse(level) ?? 0;
                                progress =
                                    box.get('UserLevelPercentage').toString();
                              } catch (error) {
                                Log.debug(error.toString());
                              }
                              // level = _bookcontroller.level;
                              // //progress = _bookcontroller.progress;
                              // progress = _userController.profile.value.levelPercentage.toString();
                              // // check last digit
                              if (bookLevel == level &&
                                  setEvaluation == true &&
                                  (isStudent || isIndividual) &&
                                  (widget.readingType ==
                                          NanhaiBookReadingTypes.library ||
                                      widget.readingType ==
                                          NanhaiBookReadingTypes.leveled)) {
                                //æš‚æ—¶æŠŠevaluationä¹¦é™å®šåœ¨1-12çº§æ‰ä¼šè·³ä¹¦
                                if (_userLevel! > 0 && _userLevel < 13) {
                                  String last =
                                      progress!.substring(progress.length - 1);
                                  //callEva = last.contains('4') || last.contains('8');
                                  callEva =
                                      last.contains('4') || last.contains('8');
                                }
                              }
                              box.put(CacheManagerKey['_callEva'].toString(),
                                  callEva);

                              if (callEva == false) {
                                if ((GetPlatform.isDesktop ||
                                        GetPlatform.isMacOS) &&
                                    !GetPlatform.isWeb) {
                                  launchInWebViewWithJavaScript(
                                      '${Constants.BaseURL}icr/student/book/$bid');
                                } else if (GetPlatform.isWeb) {
                                  box.put(
                                      CacheManagerKey['_quizAvailable']
                                          .toString(),
                                      quizAvailable);
                                  bool readComplete =
                                      currentBook.readComplete ?? false;
                                  box.put(
                                      CacheManagerKey['_readComplete']
                                          .toString(),
                                      readComplete);

                                  if (isTeacher || isAdmin) {
                                    launchInWebViewWithJavaScript(
                                        '${Constants.BaseURL}icr/student/book/$bid');
                                  } else {
                                    Navigator.pushNamed(
                                        context, '/student/book',
                                        arguments: BookArguments(
                                            bid,
                                            bcode,
                                            btitle,
                                            widget.assignmentId ?? null,
                                            widget.readingType,
                                            userName));
                                  }
                                } else {
                                  String viewMode =
                                      widget.books[index].viewMode ??
                                          'LANDSCAPE';
                                  box.put(
                                      CacheManagerKey['_viewMode'].toString(),
                                      viewMode.toString());
                                  bool quizAvailable =
                                      currentBook.quizAvailable ?? false;
                                  box.put(
                                      CacheManagerKey['_quizAvailable']
                                          .toString(),
                                      quizAvailable);
                                  bool readComplete =
                                      currentBook.readComplete ?? false;
                                  box.put(
                                      CacheManagerKey['_readComplete']
                                          .toString(),
                                      readComplete);
                                  Navigator.pushNamed(context, '/student/book',
                                      arguments: BookArguments(
                                          bid,
                                          bcode,
                                          btitle,
                                          widget.assignmentId ?? null,
                                          widget.readingType,
                                          userName));
                                }
                              } else {
                                final EvaluationController
                                    _evaluationController = Get.find();

                                _evaluationController
                                    .fetchEvaluationRandomBook(level!)
                                    .then((status) {
                                  if (status.status == 1000) {
                                    box.put(
                                        CacheManagerKey['_quizAvailable']
                                            .toString(),
                                        false);

                                    showDialog(
                                        context: context,
                                        builder: (BuildContext context) {
                                          return EvaBookDialog(
                                              title: 'Evaluation Book'.tr,
                                              message:
                                                  'Please complete this evaluation book to continue!'
                                                      .tr,
                                              level: level!,
                                              from: 'library',
                                              userName: userName);
                                        });
                                  } else {
                                    String viewMode =
                                        widget.books[index].viewMode ??
                                            'LANDSCAPE';
                                    box.put(
                                        CacheManagerKey['_viewMode'].toString(),
                                        viewMode.toString());
                                    bool quizAvailable =
                                        currentBook.quizAvailable ?? false;
                                    box.put(
                                        CacheManagerKey['_quizAvailable']
                                            .toString(),
                                        quizAvailable);
                                    bool readComplete =
                                        currentBook.readComplete ?? false;
                                    box.put(
                                        CacheManagerKey['_readComplete']
                                            .toString(),
                                        readComplete);

                                    Navigator.pushNamed(
                                        context, '/student/book',
                                        arguments: BookArguments(
                                            bid,
                                            bcode,
                                            btitle,
                                            widget.assignmentId ?? null,
                                            widget.readingType,
                                            userName));
                                  }
                                });
                              }
                            },
                            //////gap of book and title from here//////
                            child: Container(
                              margin: EdgeInsets.only(top: 12.0),
                              height: 45,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.only(top: 3.0),
                                    child: Text(
                                      bookLevel != '0'
                                          ? ' L$bookLevel  '
                                          : 'N/A',
                                      style: TextStyle(
                                          fontFamily: 'Montserrat',
                                          fontSize: 12,
                                          color: Colors.white,
                                          backgroundColor:
                                              hexStringToHexInt(color)),
                                    ),
                                  ),
                                  Expanded(
                                    child: Text(' $btitle',
                                        maxLines: 2,
                                        overflow: TextOverflow.fade,
                                        style: TextStyle(
                                            color: Get.isDarkMode
                                                ? Colors.white
                                                : Colors.black,
                                            fontSize: 14.0,
                                            fontFamily: 'Noto Sans SC')),
                                  ),
                                ],
                              ),
                            ),
                          )),
                    ],
                  ),
                ),
                /////////å³è¾¹çš„ICONç¾¤///////////
                Container(
                  margin: EdgeInsets.only(left: 6.0),
                  child: Column(
                    //mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Checkbox(
                          value: widget.books[index].selected ?? false,
                          onChanged: (value) {
                            // // var item = books
                            // //     .where((element) => element.bookId == books[index].bookId).first;
                            if (value == true) {
                              _bookcontroller.addToSelectedBookItems(
                                  widget.books[index], widget.readingType);
                            } else {
                              _bookcontroller.removeFromSelectedBookItems(
                                  widget.books[index], widget.readingType);
                            }
                            widget.books[index].selected = value;
                            //   setState(() {
                            //  books[index].selected = value;
                            // });
                          }),
                      Visibility(
                        child: Icon(Icons.book,
                            color: readComplete
                                ? hexStringToHexInt('#ffc107')
                                : Colors.white,
                            size: 21.0),
                        visible: isIndividual || isStudent,
                      ),
                      Visibility(
                        child: Padding(
                          padding: const EdgeInsets.only(top: 5),
                        ),
                        visible: isIndividual || isStudent,
                      ),
                      if (isStudent || isIndividual)
                        quizAvailable
                            ? readComplete
                                ? MouseRegion(
                                    cursor: SystemMouseCursors.click,
                                    child: GestureDetector(
                                      onTap: () {
                                        Get.to(() => BookQuizEditor(
                                              bookId: bid,
                                              bookcode: bcode,
                                              bookTitle: btitle,
                                              assignmentId:
                                                  widget.assignmentId ?? null,
                                            ));
                                        String viewMode =
                                            widget.books[index].viewMode ??
                                                'LANDSCAPE';
                                        box.put(
                                            CacheManagerKey['_viewMode']
                                                .toString(),
                                            viewMode.toString());
                                      },
                                      child: Icon(Icons.quiz_outlined,
                                          color: quizColor, size: 21.0),
                                    ))
                                : Icon(Icons.quiz_outlined,
                                    color: Colors.white, size: 21.0)
                            : Text(''),
                      // still used in teacher library
                      // if (isTeacher || isAdmin)
                      //   quizAvailable
                      //       ? new GestureDetector(
                      //           onTap: () {
                      //             Get.to(() => BookQuizReviewer(
                      //                   bookId: bid,
                      //                   bookTitle: btitle,
                      //                 ));
                      //           },
                      //           child: Icon(Icons.quiz_outlined,
                      //               color: Colors.white, size: 21.0),
                      //         )
                      //       : Padding(
                      //           padding: const EdgeInsets.only(top: 0.0),
                      //         ),
                      Padding(
                        padding: const EdgeInsets.only(top: 5),
                      ),
                      Icon(Icons.favorite_border_rounded,
                          color: inFolder
                              ? hexStringToHexInt('#ffc107')
                              : Colors.white,
                          size: 21.0),
                      Visibility(
                        visible: !isIndividual,
                        child: Padding(
                          padding: const EdgeInsets.only(top: 5),
                        ),
                      ),
                      Visibility(
                          //visible: !isIndividual,
                          visible: false,
                          child: MouseRegion(
                              cursor: SystemMouseCursors.click,
                              child: GestureDetector(
                                child: Icon(Icons.remove_red_eye_sharp,
                                    color: quickReview != ''
                                        ? hexStringToHexInt('#ffc107')
                                        : Colors.white,
                                    size: 21.0),
                                onTap: () {
                                  final AssessmentsController
                                      _assessmentsController = Get.find();
                                  if (currentBook.quickReview != null) {
                                    _assessmentsController
                                        .fetchQuestionRecordInfoDetails(
                                            currentBook.quickReview!)
                                        .then((data) {
                                      if (data != null && data.list != null) {
                                        Get.to(() => BookQuickReview(
                                            bookItem: currentBook,
                                            submited: true));
                                      } else {
                                        Get.snackbar(
                                            'Message'.tr,
                                            'Book quick review data coming soon'
                                                .tr,
                                            backgroundColor:
                                                Theme.of(context).primaryColor,
                                            colorText: Theme.of(context)
                                                .primaryColorLight,
                                            snackPosition:
                                                SnackPosition.BOTTOM);
                                      }
                                    });
                                  } else {
                                    _assessmentsController
                                        .getQuickReviewQuestionGroupByBookCode(
                                            currentBook.bookCode.toString())
                                        .then((data) {
                                      if (data?.list != null) {
                                        Get.to(() => BookQuickReview(
                                            bookItem: currentBook,
                                            readingType: widget.readingType,
                                            submited: false));
                                      } else {
                                        Get.snackbar(
                                            'Message'.tr,
                                            'Book quick review data coming soon'
                                                .tr,
                                            backgroundColor:
                                                Theme.of(context).primaryColor,
                                            colorText: Theme.of(context)
                                                .primaryColorLight,
                                            snackPosition:
                                                SnackPosition.BOTTOM);
                                      }
                                    });
                                  }
                                },
                              ))),

                      // Padding(
                      //   padding: const EdgeInsets.only(top: 5),
                      // ),
                      MouseRegion(
                          cursor: SystemMouseCursors.click,
                          child: GestureDetector(
                            child: Icon(Icons.wordpress_rounded,
                                color: word != ''
                                    ? hexStringToHexInt('#ffc107')
                                    : Colors.white,
                                size: 21.0),
                            onTap: () {
                              final KnowledgeWordsController _wordcontroller =
                                  Get.put(KnowledgeWordsController());
                              Log.debug(currentBook.bookCode);
                              _wordcontroller
                                  .fetchWordQuiz(currentBook.bookCode, null)
                                  .then((data) {
                                if (data.status == 1000 &&
                                    data.result != null) {
                                  _wordcontroller.bookCode =
                                      currentBook.bookCode;
                                  Get.to(() => WordCardQuiz(
                                        bookId: currentBook.bookId,
                                        readingType: widget.readingType,
                                      ));
                                } else {
                                  Get.delete<KnowledgeWordsController>();
                                  Get.snackbar('Message'.tr,
                                      'Word quiz data coming soon'.tr,
                                      backgroundColor:
                                          Theme.of(context).primaryColor,
                                      colorText:
                                          Theme.of(context).primaryColorLight,
                                      snackPosition: SnackPosition.BOTTOM);
                                }
                              });
                            },
                          )),
                      Visibility(
                        visible: !isIndividual,
                        child: Padding(
                          padding: const EdgeInsets.only(top: 5),
                        ),
                      ),
                      Visibility(
                          //visible: !isIndividual,
                          visible: false,
                          child: MouseRegion(
                              cursor: SystemMouseCursors.click,
                              child: GestureDetector(
                                child: Icon(Icons.policy,
                                    color: grammar != ''
                                        ? hexStringToHexInt('#ffc107')
                                        : Colors.white,
                                    size: 21.0),
                                onTap: () {
                                  final AssessmentsController
                                      _assessmentsController = Get.find();
                                  if (currentBook.grammar != null) {
                                    _assessmentsController
                                        .fetchQuestionRecordInfoDetails(
                                            currentBook.grammar!)
                                        .then((data) {
                                      if (data != null && data.list != null) {
                                        Get.to(() => BookGrammar(
                                            bookItem: currentBook,
                                            submited: true));
                                      } else {
                                        Get.snackbar('Message'.tr,
                                            'Grammar data coming soon'.tr,
                                            backgroundColor:
                                                Theme.of(context).primaryColor,
                                            colorText: Theme.of(context)
                                                .primaryColorLight,
                                            snackPosition:
                                                SnackPosition.BOTTOM);
                                      }
                                    });
                                  } else {
                                    // _assessmentsController
                                    //     .getGrammarGroupQuestionByBookCode(
                                    //         currentBook.bookCode.toString())
                                    // use demo bookcode temptly -- EB0001 --BQ0016 --APPLE0031 --APPLE0036
                                    _assessmentsController
                                        .getGrammarGroupQuestionByBookCode(
                                            'EB0001')
                                        .then((data) {
                                      if (data != null && data.length > 0) {
                                        Get.to(() => BookGrammar(
                                            bookItem: currentBook,
                                            readingType: widget.readingType,
                                            submited: false));
                                      } else {
                                        Get.snackbar('Message'.tr,
                                            'Grammar data coming soon'.tr,
                                            backgroundColor:
                                                Theme.of(context).primaryColor,
                                            colorText: Theme.of(context)
                                                .primaryColorLight,
                                            snackPosition:
                                                SnackPosition.BOTTOM);
                                      }
                                    });
                                  }
                                },
                              ))),

                      Padding(
                        padding: const EdgeInsets.only(top: 5),
                      ),
                      inAudioPlaylist
                          ? Icon(Icons.audiotrack,
                              color: hexStringToHexInt('#ffc107'), size: 21.0)
                          : Padding(
                              padding: const EdgeInsets.only(top: 22),
                            ),
                    ],
                  ),
                )
              ],
            ),
          );
        });
  }
}
